<?php
/**
 * Created by PhpStorm.
 * User: Kevin
 * Date: 2018/7/17
 * Time: 10:51
 */
namespace app\home\controller;
//include '/data/wwwroot/south.xuanwumobile.com/vendor/autoload.php'; // 引入 composer 入口文件
// 一些配置
use think\Db;
use think\Config;
use EasyWeChat\Foundation\Application;

class Wechat extends Common
{
    /**
     * 账号密码登录
     * @return bool
     * 参数：账号、密码
     * 返回值：0参数错误，1手机号码错误，2密码格式错误，3没有此用户，4密码错误，5成功
     */
    public  function index(){

        $options = Config::get('wechat');
        // 使用配置来初始化一个项目。
        $app = new Application($options);
        $server = $app->server;
        /*-------------------------------------------------------------------------*/
        $menu = $app->menu;
        $buttons = [
            [
                "name" => "我的",
                "sub_button" => [
                    [
                        "type" => "view",
                        "name" => "首页",
                        "url" => "http://south.xuanwumobile.com/home/first/index"
                    ],
                    [
                        "type" => "view",
                        "name" => "机构",
                        "url" => "http://south.xuanwumobile.com/home/Mechanism/index"
                    ],
                    [
                        "type" => "view",
                        "name" => "资讯",
                        "url" => "http://south.xuanwumobile.com/home/Information/index"
                    ],
                    [
                        "type" => "view",
                        "name" => "课程",
                        "url" => "http://south.xuanwumobile.com/home/Classroom/index"
                    ],
                    [
                        "type" => "view",
                        "name" => "我的",
                        "url" => "http://south.xuanwumobile.com/home/My/index"
                    ],
                    [
                        "type" => "click",
                        "name" => "赞23",
                        "key" => "V1001_GOOD"
                    ]

                ]
            ]
        ];
        $menu->add($buttons);
        /*-------------------------------------------------------------------------*/
        $server->setMessageHandler(function ($message) {
            $openid = $message->FromUserName; // 用户的 openid...
            $ty = $message->MsgType; // 消息类型：event, text....
            return "opnid:{$openid},type:{$ty}";
            //如果是关注事件
//            $guanzhu = $message->Event;
//            if($guanzhu == 'subscribe'){
//                return "欢迎关注公众号！";
//            }
            //============================

        });
        $response = $app->server->serve();
        // 将响应输出
        $response->send(); // Laravel 里请使用：return $response;
    }

    /**
     * 手机登录或注册时发送的验证码
     * @return bool
     * 参数：phone type(1是登录和更换手机号(第一步) 2是注册和更换手机号(第二步) 3是忘记密码)
     * 返回值：0参数错误，1手机格式错误，21登录无此号，22注册有此号，3验证码发送失败，4返回md5加密验证码
     */
    public  function getPhoneCode(){//echo 1;die;
        header("Access-Control-Allow-Origin:*");
        extract(input());
        if(!isset($phone) || !isset($type)){
            return json(['code'=>0,'msg'=>'参数错误']);
        }
        $num = GetRandCode();
        if(!preg_match("/^1[3456789]\d{9}$/", $phone)){
            return json(['code'=>1,'msg'=>'请填写正确的手机号码']);
        }
        $username = Db::table('up_u_user')->where('user_phone',$phone)->find();
        if(empty($username) && $type==1){
            return json(['code'=>21,'msg'=>'没有此手机号码用户']);
        }
        if(empty($username) && $type==3){
            return json(['code'=>21,'msg'=>'没有此手机号码用户']);
        }
        if(!empty($username) && $type==2){
            return json(['code'=>22,'msg'=>'已经有此手机号码用户']);
        }
        $templateid = config('yzx')['templateid'];
        $sendres = YzxSms($templateid, $num, $phone, '');
        if($sendres['code'] != '00000'){
            return json(['code'=>3,'msg'=>$sendres['msg']]);
        }else {
            //=============================
            $isset = Db::table('up_phonecode')->where('phone', $phone)->find();
            if ($isset) {
                $res = Db::table('up_phonecode')->where('phone', $phone)->update(['code' => md5($num), 'time2' => time(), 'code' => 0]);
            } else {
                $res = Db::table('up_phonecode')->insert(['phone' => $phone, 'code' => md5($num), 'time2' => time()]);
            }
            if (!$res) {
                return json(['code' => 31, 'msg' => '数据库操作失败']);
            }
            //===============================================
            return json(['code' => 200, 'msg' => md5($num)]);
        }
    }

    /**
     * 注册
     * @return bool
     * 参数：phone,code,name,password,major
     * 返回：0参数错误，1手机格式错误，21验证码错误，22验证码超时，3无此用户，4有其他未填项，5插入登录表失败，200成功
     */

    public  function userReg(){
        header("Access-Control-Allow-Origin:*");
        extract (input());
        if(!isset($phone) || !isset($code)){
            return json(['code'=>0,'msg'=>'参数错误']);
        }
        if(!isset($pass)){
            return json(['code'=>0,'msg'=>'参数错误']);
        }
        if(!preg_match("/^1[3456789]\d{9}$/", $phone)){
            return json(['code'=>1,'msg'=>'请填写正确的手机号码']);
        }
        $username = Db::table('up_u_user')->where('user_phone',$phone)->find();
        if(!empty($username)){
            return json(['code'=>3,'msg'=>'已经有此手机号码用户']);
        }
        if($pass=='' || $code==''){
            return json(['code'=>4,'msg'=>'有未填项，请检查']);
        }
        //=============================================
        $res = Db::table('up_phonecode')->where('phone',$phone)->find();
        //=============================================================
        if($code != $res['code']){
            return json(['code'=>21,'msg'=>'验证码错误']);
        }
        $now = time();
        if($now - $res['time2'] >= 601){
            return json(['code'=>22,'msg'=>'验证码超时']);
        }
        if($res['code']==1){
            return json(['code'=>23,'msg'=>'验证码已使用']);
        }
        $token = md5(date('YmdHis').rand(100000,999999));
        $data = array();
        $data['user_password'] = md5($pass);
        $data['user_time'] = date('Y-m-d H:i:s');
        $data['user_time'] = date('Y-m-d');
        $data['user_token'] = $token;
        $data['user_phone'] = $phone;
        $data['user_attestation'] = 1;//未认证
        $data['user_username'] = '用户' . rand(100000,999999);//未认证
        $id = Db::name('u_user')->insertGetId($data);
        if($id){
            $user = Db::table('up_u_user')
                ->where('user_id',$id)
                ->find();
            $rytoken = $this->rongyun($user['user_id'],$user['user_username'],$user['user_image']);
            $user['rytoken'] = $rytoken['token'];
            return json(['code'=>200,'msg'=>$user]);
        }else{
            return json(['code'=>5,'msg'=>'生成登录数据失败']);
        }
    }

    /**
     * 忘记密码或修改密码
     * @return bool
     * 参数：phone,code
     * 返回：0参数错误，1手机格式错误，21验证码错误，22验证码超时，3无此用户，200成功
     */

    public  function forgetPass(){
        header("Access-Control-Allow-Origin:*");
        extract(input());
        if(!isset($phone) || !isset($code)){
            return json(['code'=>0,'msg'=>'参数错误']);
        }
        if(!preg_match("/^1[3456789]\d{9}$/", $phone)){
            return json(['code'=>1,'msg'=>'请填写正确的手机号码']);
        }
        if($newpass == '' || $code == ''){
            return json(['code'=>2,'msg'=>'有未填项']);
        }
        $username = Db::table('up_u_user')->where('user_phone',$phone)->find();
        if(empty($username)){
            return json(['code'=>3,'msg'=>'没有此手机号码用户']);
        }
        //=============================================
        $res = Db::table('up_phonecode')->where('phone',$phone)->find();
        //=============================================================
        if($code != $res['code']){
            return json(['code'=>21,'msg'=>'验证码错误']);
        }
        $now = time();
        if($now - $res['time2'] >= 601){
            return json(['code'=>22,'msg'=>'验证码超时']);
        }
        if($res['code']==1){
            return json(['code'=>23,'msg'=>'验证码已使用']);
        }
        //TODO 修改密码成功后如果直接登录那么就要更新token
        $token = md5(date('YmdHis').rand(100000,999999));
        //,'user_token'=>$token
        $update = array();
        $update['user_password'] = md5($newpass);
        if($type == 1){
            $update['user_token'] = $token;
        }
        $res = Db::table('up_u_user')->where('user_phone',$phone)->update($update);
        Db::table('up_phonecode')->where('phone',$phone)->update(['code'=>1]);
        if($res){
            $user = Db::table('up_u_user')->where('user_phone',$phone)->find();
            if($type == 1){
                $rytoken = $this->rongyun($user['user_id'],$user['user_username'],$user['user_image']);
                $user['rytoken'] = $rytoken['token'];
            }
            return json(['code'=>200,'msg'=>$user]);
        }else{
            return json(['code'=>3,'msg'=>'密码重置失败']);
        }
    }

    //================第三方登录====================

    /**
     * 微信或者qq登录
     * wqtoken,type(1是微信，2是qq)
     * @return string
     */
    public  function wqLogin()
    {
        header("Access-Control-Allow-Origin:*");
        extract(input());
        if($type == 1){
            $field = 'user_wx_token';
        }else{
            $field = 'user_qq_token';
        }
        $username = Db::table('ew_u_user')->where($field, $wxtoken)->find();
        if (!empty($username)) {
            $token = md5(date('YmdHis') . rand(100000, 999999));
            $res = Db::table('ew_u_user')->where($field, $wxtoken)->update(['user_token' => $token]);
            if ($res) {
                //===禁用和启用====
                if($username['user_code'] != 1){
                    return json(['code' => 0, 'msg' => '对不起，您无权登录，请联系客服']);
                }
                //======end======
                $user = Db::table('ew_u_user')->where($field, $wxtoken)->find();
                $rytoken = $this->rongyun($user['user_id'], $user['user_username'], $user['user_image']);
                if($rytoken['code'] != 200){
                    return json(['code'=>0,'msg'=>$rytoken['errorMessage']]);
                }
                $user['rytoken'] = $rytoken['token'];
                return json(['code' => 200, 'msg' => $user]);
            } else {
                return json(['code' => 3, 'msg' => '数据库出错']);
            }
        }else{
            return json(['code' => 4, 'msg' => '查无此人']);
        }

    }
    /**
     * 微信或者qq第一次登录
     * wqtoken，phone，code，name，image，type
     * @return string
     */
    public  function wqFirstLogin()
    {
        header("Access-Control-Allow-Origin:*");
        extract(input());
        if($type == 1){
            $field = '_wx_';
        }else{
            $field = '_qq_';
        }
        if(!preg_match("/^1[3456789]\d{9}$/", $phone)){
            return json(['code'=>1,'msg'=>'请填写正确的手机号码']);
        }
        $username = Db::table('ew_u_user')->where('user_phone',$phone)->find();
        if(!empty($username)){
            return json(['code'=>3,'msg'=>'已经有此手机号码用户']);
        }
        if($code==''){
            return json(['code'=>4,'msg'=>'有未填项，请检查']);
        }
        //=============================================
        $res = Db::table('ew_phonecode')->where('phone',$phone)->find();
        //=============================================================
        if($code != $res['code']){
            return json(['code'=>21,'msg'=>'验证码错误']);
        }
        $now = time();
        if($now - $res['time2'] >= 601){
            return json(['code'=>22,'msg'=>'验证码超时']);
        }
        if($res['code']==1){
            return json(['code'=>23,'msg'=>'验证码已使用']);
        }
        $token = md5(date('YmdHis').rand(100000,999999));
        $data = array();
        $data['user_time'] = date('Y-m-d H:i:s');
        $data['user_token'] = $token;
        $data['user_phone'] = $phone;
        $data['user'.$field.'token'] = $wqtoken;
        $data['user'.$field.'nickname'] = $name;
        $data['user'.$field.'image'] = $image;
        $data['user_image'] = $image;//用户名字和头像同步一下
        $data['user_username'] = $name;//
        if($name == ''){
            $data['user_username'] = '用户' . rand(100000,999999);//未认证
        }
        $id = Db::name('u_user')->insertGetId($data);
        if($id){
            $user = Db::table('ew_u_user')
                ->where('user_id',$id)
                //->field('user_id,user_username,user_image')
                ->find();
            Db::table('ew_phonecode')->where('phone',$phone)->update(['code'=>1]);
            $rytoken = $this->rongyun($user['user_id'],$user['user_username'],$user['user_image']);
            if($rytoken['code'] != 200){
                return json(['code'=>0,'msg'=>$rytoken['errorMessage']]);
            }
            $user['rytoken'] = $rytoken['token'];
            return json(['code'=>200,'msg'=>$user]);
        }else{
            return json(['code'=>5,'msg'=>'生成登录数据失败']);
        }

    }
}